<?php
namespace app\common\constant;

use app\admin\model\Admin;
use CURLFile;
use think\Db;
use think\Log;

/**
 * 公共常用方法
 */
class Common
{
    /**
     *验证邮箱是否正确
     */
    public static function checkEmail($email)
    {
        if (!preg_match("/^([a-zA-Z0-9-_]*[.]?[a-zA-Z0-9-_]+)*@([a-zA-Z0-9-_]*[.]?[a-zA-Z0-9-_]+)+([.][a-zA-Z0-9]{2,6})+$/", $email)) {
            return false;
        }
        return true;
    }

    /**
     *验证手机号的格式
     */
    public static function checkMobileFormat($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[\d]{9}$|^15[\d]{9}$|^16[\d]{9}$|^17[\d]{9}$|^18[\d]{9}$|^19[\d]{9}$#', $mobile) ? true : false;
    }

    /**
     * 验证区号+电话号码+分机号
     * @param $telphone
     * @return bool
     */
    public static function checkTelphoneFormat($telphone)
    {
        if (empty($telphone)) {
            return false;
        }
        return preg_match('/^(((\d{3,4}\-)?(\d{5,8})(\-\d{1,5})?)|^(\d{7,17}))$/', $telphone) ? true : false;
    }

    /*
     * microsecond 微秒     millisecond 毫秒
     *返回时间戳的毫秒数部分
     */
    public static function getMilliSecond()
    {
        list($usec, $sec) = explode(" ", microtime());
        $msec = round($usec * 1000);
        return $msec;
    }

    /**
     *获取时间戳
     */
    public static function getMilliTimestamp()
    {
        $millisecond = self::getMilliSecond();
        $millisecond = str_pad($millisecond, 3, '0', STR_PAD_RIGHT);
        return date('YmdHis') . $millisecond;
    }

    /**
     *获取页面的分页数量
     */
    public static function getPageNums($totalCount, $pageSize)
    {
        $pageNum = 1;
        if ($totalCount == 0)
            $pageNum = 0;
        else if ($totalCount % $pageSize == 0) {
            $pageNum = $totalCount / $pageSize;
        } else {
            $pageNum = intval($totalCount / $pageSize) + 1;
        }
        return $pageNum;
    }

    /**
     *获取隐藏式的手机号
     */
    public static function getHideMobile($mobile)
    {
        if (empty($mobile)) {
            return '';
        }
        return substr_replace($mobile, "****", 3, 4);
    }


    /**
     * 根据区间获取区间范围内的月份
     * @param start 开始时间 2017-06
     * @param end 结束时间
     * @param format 格式 Ym,Y-m
     */
    public static function getMonths($start, $end, $format)
    {
        if (empty($start) || empty($end) || empty($format) || !in_array($format, ['Ym', 'Y-m'])) {
            return null;
        }

        $start = strtotime($start);
        $end = strtotime($end);
        if ($start > $end) {
            return null;
        }

        $months = [];

        do {
            $months[] = date($format, $start);
            $start = strtotime('1 month', $start);
        } while ($start <= $end);

        return $months;
    }

    /**
     * 获取两个时间相差的月份
     * @param time1 时间1
     * @param time2 时间2
     */
    public static function diffMonths($date1, $date2)
    {
        $large = date('Y-m', strtotime($date2));
        $small = date('Y-m', strtotime($date1));
        if (strtotime($date1) > strtotime($date2)) {
            $large = date('Y-m', strtotime($date1));
            $small = date('Y-m', strtotime($date2));
        }

        list($y1, $m1) = explode('-', $small);
        list($y2, $m2) = explode('-', $large);

        $y = $y2 - $y1;
        $m = (12 - $m1) + ($y - 1) * 12 + $m2;

        return $m;
    }

    /**
     * 获取月份的数量
     * @param start 'yyyy-mm-dd'
     * @param end 'yyyy-mm-dd'
     */
    public static function getMonthCount($start, $end)
    {
        $start = date('Y-m-01', strtotime($start));
        $end = date('Y-m-01', strtotime($end));

        $count = 1;
        do {
            $tmpTime = date('Y-m-01', strtotime('+' . $count . ' month', strtotime($start)));
            if (strtotime($tmpTime) > strtotime($end)) {
                break;
            } elseif (strtotime($tmpTime) == strtotime($end)) {
                $count++;
                break;
            }
            $count++;
        } while (true);
        return $count;
    }


    /**
     * 获取当前月份的所有日期
     */
    public static function getDays($month, $format)
    {
        $days = date("t", strtotime($month));
        $result = array();
        for ($i = 1; $i <= $days; $i++) {
            if ($format = 'Ymd') {
                $result[] = date("Ym", strtotime($month)) . str_pad($i, 2, '0', STR_PAD_LEFT);
            } elseif ($format == 'Y-m-d') {
                $result[] = date("Y-m", strtotime($month)) . "-" . $i;
            }
        }
        return $result;
    }

    /**
     *获取隐藏式的邮箱
     */
    public static function getHideEmail($email)
    {
        if (empty($email)) {
            return '';
        }
        $emailArr = explode('@', $email);
        if (strlen($emailArr[0]) > 4) {
            $emailArr[0] = substr($emailArr[0], 0, 4);
        }
        $emailArr[0] .= '*****';
        return implode('@', $emailArr);
    }

    /**
     * 生成随机码
     */
    public static function generateRandCode($length, $chars)
    {
        // 密码字符集，可任意添加你需要的字符
        if (empty($chars)) {
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        }
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $code;
    }

    /**
     * 根据时间生成随机码
     */
    public static function generateRandCodeWithTime($len)
    {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $string = time();
        for (; $len >= 1; $len--) {
            $position = rand() % strlen($chars);
            $position2 = rand() % strlen($string);
            $string = substr_replace($string, substr($chars, $position, 1), $position2, 0);
        }
        return $string;
    }

    /**
     * 生成3rdSession
     */
    public static function getRandomFromDev($len)
    {
        $fp = @fopen('/dev/urandom', 'rb');
        $result = '';
        if ($fp !== FALSE) {
            $result .= @fread($fp, $len);
            @fclose($fp);
        } else {
//			trigger_error('Can not open /dev/urandom.');
            //生成一串随机数，类似：zUdL-gFMygQcsKzd
            //取随机字符串
            $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz-";
            $max = strlen($strPol) - 1;
            for ($i = 0; $i < $len; $i++) {
                $result .= $strPol[mt_rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
            }
        }
        // convert from binary to string
        $result = base64_encode($result);
        // remove none url chars
        $result = strtr($result, '+/', '-_');
        return substr($result, 0, $len);
    }

    /**
     * 获取除法的结果
     * @param first 分子
     * @param second 分母
     * @param isPercent 是否是百分比
     */
    public static function getDivResult($first, $second, $isPercent)
    {
        if ($second == 0) {//分母为0返回0
            return 0;
        }
        if ($isPercent) {
            //百分比形式,结果乘以100
            return bcdiv($first * 100, $second, 2);
        }
        return bcdiv($first, $second, 2);
    }

    /**
     * 获取一个月的第一号
     * @param month 格式 201909
     */
    public static function getMonthFirstDay($month)
    {
        return substr($month, 0, 4) . '-' . substr($month, 4, 2) . '-01';
    }

    /**
     * 获取某个时间的季度信息
     * @param date : 2018-07-02 (xx:xx:xx) 只要是标准时间格式即可
     */
    public static function getCurQuarter($date = null)
    {
        //默认获取当前月份
        $month = date("m");
        if (!empty($date)) {
            $month = date("m", strtotime($date));
        }
        $quarter = 1;//默认第一季度
        switch ($month) {
            case '1':
            case '2':
            case '3':
                $quarter = 1;
                break;
            case '4':
            case '5':
            case '6':
                $quarter = 2;
                break;
            case '7':
            case '8':
            case '9':
                $quarter = 3;
                break;
            case '10':
            case '11':
            case '12':
                $quarter = 4;
                break;
            default:
                break;
        }
        return $quarter;
    }

    /**
     * 获取某个时间的季度第一天时间
     * @param date : 2018-07-02 (xx:xx:xx) 只要是标准时间格式即可
     * @return day : 2018-01-01 00:00:00
     */
    public static function getCurQuarterFirstDay($date = null)
    {
        //默认获取当前月份
        $quarter = self::getCurQuarter($date);

        switch ($quarter) {
            case 1:
                $day = date("Y-01-01 00:00:00");
                break;
            case 2:
                $day = date("Y-04-01 00:00:00");
                break;
            case 3:
                $day = date("Y-07-01 00:00:00");
                break;
            case 4:
                $day = date("Y-10-01 00:00:00");
                break;
        }
        return $day;
    }

    /**
     * 获得给定时间的时间间隔
     * @param $day1 ,$day2 2018-08-08 (xx:xx:xx) 标准时间格式
     */
    public static function getTimeSpanDays($day1, $day2)
    {
        $date1 = date_create($day1);
        $date2 = date_create($day2);
        $diffDays = date_diff($date1, $date2)->days;
        return $diffDays;
    }

    /**
     * 数组转换对象
     *
     * @param $e 数组
     * @return object|void
     */
    public static function arrayToObject($e)
    {
        if (gettype($e) != 'array')
            return;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'array' || getType($v) == 'object')
                $e[$k] = (object)self::arrayToObject($v);
        }
        return (object)$e;
    }

    /**
     * 对象转换数组
     *
     * @param $e StdClass对象实例
     * @return array|void
     */
    public static function objectToArray($e)
    {
        $e = (array)$e;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'resource') return;
            if (gettype($v) == 'object' || gettype($v) == 'array')
                $e[$k] = (array)self::objectToArray($v);
        }
        return $e;
    }

    /**
     * 返回给定字符串中的所有汉字
     * @param $str 给定的字符串
     * @param $cnStr 返回的汉字拼接的字符串
     * @param $cnNum 汉字的数量
     */
    public static function getCnStrInStr($str, &$cnStr, &$cnNum)
    {
        preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $match);
        $cnNum = count($match[0]);
        $cnStr = join('', $match[0]);
        return true;
    }

    /**
     * 清除富文本编辑器的内容
     */
    public static function clearEditorHtml($content)
    {
        if ($content == '') {
            return '';
        }
        //去除空格
        $content = str_replace(["\r\n", "\r", "\n"], '', $content);
        //去除style
        $content = preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si", "", $content);
        //去除script
        $content = preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si", "", $content);
        return $content;
    }

    /**
     * 获取季度数量
     */
    public static function getQuarterCount($start, $end)
    {
        $start = date('Y-m-01', strtotime($start));
        $end = date('Y-m-01', strtotime($end));
        $count = 1;
        $quarters = [];
        do {
            $tmpTime = date('Y-m-01', strtotime('+' . $count . ' month', strtotime($start)));
            $month = date('m', strtotime($tmpTime));
            switch ($month) {
                case '1':
                case '2':
                case '3':
                    $quarters[] = date('Y', strtotime($tmpTime)) . '01';
                    break;
                case '4':
                case '5':
                case '6':
                    $quarters[] = date('Y', strtotime($tmpTime)) . '02';
                    break;
                case '7':
                case '8':
                case '9':
                    $quarters[] = date('Y', strtotime($tmpTime)) . '03';
                    break;
                case '10':
                case '11':
                case '12':
                    $quarters[] = date('Y', strtotime($tmpTime)) . '04';
                    break;
                default:
                    break;
            }
            if (strtotime($tmpTime) >= strtotime($end)) {
                break;
            }
            $count++;
        } while (true);
        $quarters = array_unique($quarters);
        return count($quarters);
    }

    /**
     * 获取两个日期之间的所有日期
     */
    public static function generateDateRange($startDate, $endDate)
    {
        $dates = [];
        $startDate = Carbon::parse($startDate);
        $endDate = Carbon::parse($endDate);
        for ($date = $startDate; $date->lte($endDate); $date->addDay()) {
            $dates[] = $date->format('Y-m-d');
        }
        return $dates;
    }

    /**
     * 获取两个数组交叉拼接的值
     */
    public static function getCombineResult($array, $array2)
    {
        $arr = [];
        foreach ($array as $key => $item) {
            foreach ($array2 as $item2) {
                $arr[] = $item . ',' . $item2;
            }
        }
        return $arr;
    }


    /**
     * 身份证号验证
     * @param $id
     * @return bool
     */
    public static function is_idcard($id)
    {
        //把字符串转换为大写
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if (!preg_match($regx, $id)) {
            return FALSE;
        }
        //检查15位
        if (15 == strlen($id)) {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) {
                return FALSE;
            } else {
                return TRUE;
            }
        } else {      //检查18位
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) { //检查生日日期是否正确
                return FALSE;
            } else {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ($i = 0; $i < 17; $i++) {
//                    $b = (int) $id{$i};//写法废弃
                    $b = (int)substr($id, $i, 1);
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id, 17, 1)) {
                    return FALSE;
                } else {
                    return TRUE;
                }
            }
        }
    }

    /**
     * 统一社会信用代码验证。
     * 由于福建试点时发放的统一社会信用代码，不符合目前验证规则，故不进行加权验证。
     * @param $taxCode
     * @return bool
     */
    public static function isTaxCode($taxCode)
    {
        //把字符串转换为大写
        $taxCode = strtoupper($taxCode);
        if (18 != strlen($taxCode)) { //检查18位
            return FALSE;
        } else {
            $one = '159Y';//第一位可以出现的字符
            $two = '12391';//第二位可以出现的字符
            if (!strstr($one, $taxCode['0']) || !strstr($two, $taxCode['1']) || !empty($array[substr($taxCode, 2, 6)])) {
                return FALSE;
            } else {
                //检查行政区划码,91350100M0000T7G5N
                $tempAreaCode = substr($taxCode, 2, 2);
                //var_dump($tempAreaCode);
                if ($tempAreaCode == '35') {
                    //福建省的直接验证通过
                    return TRUE;
                } else {
                    //其他省份需要进行加权验证
                    $sum = 0;
                    $wi = array(1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28);//加权因子数值
                    $list = array('A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'J' => 18, 'K' => 19, 'L' => 20, 'M' => 21, 'N' => 22, 'P' => 23, 'Q' => 24, 'R' => 25, 'T' => 26, 'U' => 27, 'W' => 28, 'X' => 29, 'Y' => 30);//值转换
                    //获取字符串数据
                    $str_organization = substr($taxCode, 0, 17);
                    //循环计算17位数据的值
                    for ($i = 0; $i < 17; $i++) {
                        $tempCode = $str_organization[$i];
                        //判断是否是字母，如果是替换值
                        if (preg_match('/^[A-Z]+$/', $tempCode)) {
                            foreach ($list as $key => $value) {
                                if ($tempCode == $key) {
                                    $replacement = $value;
                                    //替换值后计算数据
                                    $sum += $replacement * $wi[$i];
                                }
                            }
                        } else {
                            //判断不是字母，直接进行计算。
                            $sum += $str_organization[$i] * $wi[$i];
                        }
                    }
                    //进行模运算
                    $remainder = $sum % 31;
                    //获取第18位验证码
                    $tempCodes = substr($taxCode, 17, 1);
                    //如果第18位是字母，进行转化
                    if (preg_match('/^[A-Z]+$/', $tempCodes)) {
                        foreach ($list as $key => $value) {
                            if ($tempCodes == $key) {
                                $tempCodes = $value;
                            }
                        }
                    }
                    //判断余数是否为0
                    if ($remainder == 0) {
                        if ($tempCodes == $remainder) {
                            return TRUE;
                        } else {
                            return FALSE;
                        }
                    } else {
                        $difference = 31 - $remainder;
                        if ($tempCodes == $difference) {
                            return TRUE;
                        } else {
                            return FALSE;
                        }
                    }
                }
            }
        }
    }

    /**
     * 必填字段验证。
     * @param $Verification
     * @return array
     */
    public static function isVerification($Verification)
    {
        $temp = array_keys($Verification, null);
        if ($temp) {
            return $temp;
        } else {
            $temp = [];
            return $temp;
        }
    }

    /**
     * 数量变更验证。
     * @param  $Quantity
     * @return $num
     * author： jere
     * time： 2020/01/17  11:14
     */
    public static function quantityChange($Quantity)
    {
        $Quantity = intval($Quantity);
        if ($Quantity >= 10000) {
            //判断数量大于10000
            $num = floatval(number_format($Quantity / 10000, 1)) . 'W';
        } elseif ($Quantity >= 1000) {
            //判断数量大于1000
            $num = floatval(number_format($Quantity / 1000, 1)) . 'K';
        } else {
            //判断数量小于1000
            $num = $Quantity;
        }
        return $num;
    }

    /**
     * 时间格式化（时间戳）
     * @param  $ptime
     * @return $msg
     * author：jere
     * time： 2020/01/17  13:41
     */
    public static function ucTimeAgo($ptime)
    {
        //设置中国时区
        date_default_timezone_set('PRC');
        $ptime = strtotime($ptime);
        //当前时间减去输入时间等于时长
        $etime = time() - $ptime;
        if ($etime == 0) {
            $etime = 1;
        }
        //判断时长
        switch ($etime) {
            case $etime <= 60 * 5://0min< x <=5min
                $msg = '刚刚';
                break;
            case $etime > 60 * 5 && $etime <= 60 * 60://5min< x <=1h
                $msg = floor($etime / 60) . '分钟前';
                break;
            case $etime > 60 * 60 && $etime <= 24 * 60 * 60:
                $msg = date('Ymd', $ptime) == date('Ymd', time()) ? floor($etime / 3600) . '小时前' : '昨天' . date('H:i', $ptime);
                break;
            case $etime > 24 * 60 * 60 && $etime <= 2 * 24 * 60 * 60:
                $msg = date('Ymd', $ptime) + 1 == date('Ymd', time()) ? '昨天' . date('H:i', $ptime) : date('Y-m-d H:i:s', $ptime);
                break;
            case $etime > 2 * 24 * 60 * 60 && $etime <= 12 * 30 * 24 * 60 * 60:
                $msg = date('Y', $ptime) == date('Y', time()) ? date('Y-m-d H:i:s', $ptime) : date('Y-m-d H:i:s', $ptime);
                break;
            default:
                $msg = date('Y-m-d H:i:s', $ptime);
        }
        return $msg;
    }

    /**
     * 获取图片主颜色
     * @param $imgUrl
     * @return bool|string
     */
    public static function getImageColor($imgUrl)
    {
        $imageInfo = @getimagesize($imgUrl);
        if (!$imageInfo) {
            return false;
        }
        //图片类型
        $imgType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
        //对应函数
        $imageFun = 'imagecreatefrom' . ($imgType == 'jpg' ? 'jpeg' : $imgType);
        $i = $imageFun($imgUrl);
        //循环色值
        $rColorNum = $gColorNum = $bColorNum = $total = 0;
        for ($x = 0; $x < imagesx($i); $x++) {
            for ($y = 0; $y < imagesy($i); $y++) {
                $rgb = imagecolorat($i, $x, $y);
                //三通道
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
                $rColorNum += $r;
                $gColorNum += $g;
                $bColorNum += $b;
                $total++;
            }
        }
        $rgb = array();
        $rgb['r'] = round($rColorNum / $total);
        $rgb['g'] = round($gColorNum / $total);
        $rgb['b'] = round($bColorNum / $total);
        $color = self::rgb2html($rgb['r'], $rgb['g'], $rgb['b']);
        return $color;
    }

    /**
     * 颜色RGB 转 html
     * @param $r
     * @param int $g
     * @param int $b
     * @return string
     */
    public static function rgb2html($r, $g = -1, $b = -1)
    {
        if (is_array($r) && sizeof($r) == 3)
            list($r, $g, $b) = $r;
        $r = intval($r);
        $g = intval($g);
        $b = intval($b);
        $r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r));
        $g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g));
        $b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b));
        $color = (strlen($r) < 2 ? '0' : '') . $r;
        $color .= (strlen($g) < 2 ? '0' : '') . $g;
        $color .= (strlen($b) < 2 ? '0' : '') . $b;
        return '#' . $color;
    }

    /**
     * 清除内容中的class
     */
    public static function clearContent($content)
    {
        if (empty($content)) {
            return '';
        }
        //判断如果数据是数组，转成字符串返回
        if (is_array($content)) {
            $str = implode(',', $content);
            $content = $str;
        }
        $content = trim($content);// 首先去掉头尾空格
        $content = preg_replace("/\s(?=\s)/", '', $content);// 接着去掉两个空格以上的
        $content = preg_replace("/[\n\r\t]/", '', $content);// 最后将非空格替换为一个空格
        $content = preg_replace("/<!--[\w\W\r\n]*?-->/", "", $content);//注释内容
        $content = preg_replace("/<script[\s\S]*?<\/script>/i", "", $content);//script标签
        $content = preg_replace("/<style[\s\S]*?<\/style>/i", "", $content);//style标签
        $content = preg_replace('/\s(?!src)(?!href)[a-zA-Z]+=[\"]{1}[^\"]*[\"]{1}/iu', '', $content);//去除标签的属性,除src
        $content = preg_replace('/\s(?!src)(?!href)[a-zA-Z]+=[\']{1}[^\']*[\']{1}/iu', '', $content);
        //以下为特列 如果文章只剩个空div,禁止用strip_tags判断
        if (in_array($content, ['<div></div>', '<div> </div>'])) {
            $content = '';
        }
        return $content ?: '';
    }

    /**
     * 拆分url获得url中的域名
     */
    public static function getUrlHost($url)
    {
        // 判断请求类型
        $httpType = 'http://';
        if (strpos($url, 'https://') !== false) {
            $httpType = 'https://';
        }
        //去掉互联网协议请求类型
        $urlStr = str_replace($httpType, "", $url);
        //以斜杠拆分字符串成数组
        $urlArr = explode("/", $urlStr);
        //取第一个斜杠前的字符
        return $urlArr[0];
    }


    /**
     * $path保存图片的地址
     * $url要获取的远程图片地址
     */
    public static function getImg($path, $url)
    {
        //获取图片格式，进行处理
        // 判断请求类型
        $httpType = 'http://';
        if (strpos($url, 'https://') !== false) {
            $httpType = 'https://';
        }
        $host = self::getUrlHost($url);
        //获取图片的域名地址
        $wxImage = $httpType . $host;
        $type = '';
        //判断如果已经替换过了，直接跳过
        if (strpos($wxImage, 'wx.qlogo.cn') !== false) {
            $ext = 'jpeg';
            $type = 'wx';
        } else {
            $aext = explode('.', $url);
            $ext = end($aext);
        }
        //设置图片名称
        $imageName = "tmp" . date("His", time()) . rand(1111, 9999) . '.' . $ext;
        //图片路径
        $imageSrc = $path . '/' . $imageName;
        //判断是否是网络地址
        if (@fopen($url, 'r')) {
            //图片是网络图片
            //获取线上图片地址
            if ($type == 'wx') {
                if (@file_get_contents($url) === false) {
                    $imageSrc = null;
                } else {
                    $source = @file_get_contents($url);
                    if (empty($source)) {
                        $imageSrc = null;
                    }
                    $img_content = base64_encode($source);
                    //将图片内容放进本地目录
                    @file_put_contents($imageSrc, base64_decode($img_content));
                }
            } else {
                if (@file_get_contents($url) === false) {
                    $imageSrc = null;
                } else {
                    $source = @file_get_contents($url);
                    if (empty($source)) {
                        $imageSrc = null;
                    }
                    //将图片内容放进本地目录
                    @file_put_contents($imageSrc, $source);
                }
            }
        } else {
            //图片不是网络图片
            $imageSrc = null;
        }
        $data = [
            "originalName" => $url,
            "filePath" => $imageSrc,
            "extension" => $ext
        ];
        return $data;
    }

    /**
     * $posturl上传图片的地址
     * $path本地图片所在的地址
     */
    public static function postImg($posturl, $path, $moduletype)
    {
        //新建一个使用curl调用一个上传文件的接口
        $obj = new CurlFile($path);
        //必须指定文件类型，否则会默认为application/octet-stream，二进制流文件</span>
        $obj->setMimeType("application/octet-stream");
        //设置post请求参数
        $post['file'] = $obj;
        $post['moduletype'] = $moduletype;
        $post['type'] = 1;
        //初始化新的会话
        $ch = curl_init();
        //为 cURL 传输会话批量设置选项
        curl_setopt($ch, CURLOPT_HEADER, false);
        //启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_URL, $posturl);//上传类
        $info = curl_exec($ch);
        curl_close($ch);
        $info = json_decode($info, true);
        $img = '';
        if (isset($info['data'])) {
            foreach ($info['data'] as $key => $value) {
                $img = $value['path'];
            }
        }
        return $img;
    }

    /**
     *提取URL
     */
    public static function getFileUrl($content)
    {
        preg_match_all("'<\s*a\s.*?href\s*=\s*([\"\'])?(?(1)(.*?)\\1|([^\s\>]+))[^>]*>?(.*?)</a>'isx", $content, $links);
        while (list($key, $val) = each($links[2])) {
            if (!empty($val))
                $match[] = $val;
        }
        while (list($key, $val) = each($links[3])) {
            if (!empty($val))
                $match[] = $val;
        }
        return $match;
    }

    /**
     *提取内容中图片
     */
    public static function getPicUrl($content)
    {
        //正则
        $pattern = "/<[img|IMG].*? src=[\'|\"](.*?(?:[\.gif|\.jpg|\.jpeg|\.JPG|\.JPEG|\.GIF|\.PNG|\.png]))[\'|\"].*?[\/]?>/";
        //匹配图片
        preg_match_all($pattern, $content, $match);
        //返回所有图片的路径
        return $match[1];
    }

    /**
     * 删除指定标签
     *
     * @param array $tags 删除的标签  数组形式
     * @param string $str html字符串
     * @param bool $content true保留标签的内容text
     * @return mixed
     */
    public static function stripHtmlTags($tags, $str, $content = true)
    {
        $html = [];
        // 是否保留标签内的text字符
        if ($content) {
            foreach ($tags as $tag) {
                $html[] = '/(<' . $tag . '.*?>(.|\n)*?<\/' . $tag . '>)/is';
            }
        } else {
            foreach ($tags as $tag) {
                $html[] = "/(<(?:\/" . $tag . "|" . $tag . ")[^>]*>)/is";
            }
        }
        $data = preg_replace($html, '', $str);
        return $data;
    }

    /**
     * 格式化金额
     * 大于等于10000，处理为以"万"单位展示
     * 否则原值输出
     * @param $price
     * @return int|string 保留2位小数
     */
    public static function formatAmount($price)
    {
        $newPrice = floatval($price);
        if (bccomp($newPrice, 10000, 2) >= 0) {
            //判断数量大于等于10000
            $num = (number_format($newPrice / 10000, 2)) . '万';
        } else {
            //判断数量小于10000
            $num = number_format($newPrice, 2, '.', '');
        }
        return $num;
    }

    /**
     * 转换文件大小
     * @param $file_size int B字节
     * @return string KB or MB or GB
     */
    public static function formatFileSize($file_size)
    {
        $file_size = intval($file_size);
        $file_size = ceil($file_size / 1024);//转化KB
        $gb = $file_size / (1024 * 1024);
        $mb = $file_size / 1024;
        if ($gb >= 1) {//GB
            $new_size = round($gb, 1) . 'GB';
        } elseif ($mb >= 100) {//MB
            $new_size = round($gb, 1) . 'GB';
        } elseif ($mb >= 1) {
            $new_size = round($mb, 1) . 'MB';
        } elseif ($file_size >= 100) {
            $new_size = round($file_size / 1024, 1) . 'MB';
        } else {
            $new_size = $file_size . 'KB';
        }
        return $new_size;
    }

    /**
     * 微信 msg_sec_check接口
     */
    public static function checkContent($content)
    {
        //$wxMgr = new Weixin;
        //$accessToken = $wxMgr->getWxAccessToken();
        $accessToken = '';
        $url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $accessToken;
        $data = json_encode(array('content' => $content), JSON_UNESCAPED_UNICODE);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url); // url
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // json数据
        $res = curl_exec($ch); // 返回值
        curl_close($ch);
        $result = json_decode($res, true);
        return $result;
    }

    /**
     * 微信图片安全内容检测接口
     */
    public static function checkImage($img)
    {
        $media = @file_get_contents($img);
        if (empty($media)) {
            return true;
        }
        $url = 'https://api.weixin.qq.com/wxa/img_sec_check?access_token=';
        $boundary = "----" . md5(strtotime(date('Y-m-d H:i:s')));
        $formdata = "--" . $boundary . "\r\n";
        $formdata .= "Content-Disposition: form-data; name=\"upload\"; filename=\"upload.jpg\"\r\n";
        $formdata .= "Content-type: application/octet-stream\r\n\r\n";
        $formdata .= $media . "\r\n";
        $formdata .= "--" . $boundary . "\r\n" . "--\r\n\r\n";
        //$wxMgr = new Weixin;
        //$accessToken = $wxMgr->getWxAccessToken();
        $accessToken = '';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url . $accessToken);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $formdata);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Content-Type: multipart/form-data; boundary=" . $boundary,
            "Content-Length: " . strlen($formdata)
        ]);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        $resultObj = json_decode($result);
        return $resultObj;
    }

    /**
     * 替换微信名中的表情符号
     * @param $text string 包含变轻符号的字符串
     * @param $replaceTo string 要将表情符号替换成自己设置的 字符
     * @return null|string|string[]
     */
    public static function filterEmoji($text, $replaceTo = '')
    {
        $clean_text = "";
        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace($regexEmoticons, $replaceTo, $text);
        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace($regexSymbols, $replaceTo, $clean_text);
        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace($regexTransport, $replaceTo, $clean_text);
        // Match Miscellaneous Symbols
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $clean_text = preg_replace($regexMisc, $replaceTo, $clean_text);
        // Match Dingbats
        $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
        $clean_text = preg_replace($regexDingbats, $replaceTo, $clean_text);
        return $clean_text;
    }

    /**
     * 将科学计数法的数字转换为正常的数字
     * 为了将数字处理完美一些，使用部分正则是可以接受的
     * @param string $number
     * @return string
     * @author loveyu
     */
    public static function convert_scientific_number_to_normal($number)
    {
        if (stripos($number, 'e') === false) {
            //判断是否为科学计数法
            return $number;
        }
        if (!preg_match(
            "/^([\\d.]+)[eE]([\\d\\-\\+]+)$/",
            str_replace(array(" ", ","), "", trim($number)), $matches)
        ) {
            //提取科学计数法中有效的数据，无法处理则直接返回
            return $number;
        }
        //对数字前后的0和点进行处理，防止数据干扰，实际上正确的科学计数法没有这个问题
        $data = preg_replace(array("/^[0]+/"), "", rtrim($matches[1], "0."));
        $length = (int)$matches[2];
        if ($data[0] == ".") {
            //由于最前面的0可能被替换掉了，这里是小数要将0补齐
            $data = "0{$data}";
        }
        //这里有一种特殊可能，无需处理
        if ($length == 0) {
            return $data;
        }
        //记住当前小数点的位置，用于判断左右移动
        $dot_position = strpos($data, ".");
        if ($dot_position === false) {
            $dot_position = strlen($data);
        }
        //正式数据处理中，是不需要点号的，最后输出时会添加上去
        $data = str_replace(".", "", $data);
        if ($length > 0) {
            //如果科学计数长度大于0
            //获取要添加0的个数，并在数据后面补充
            $repeat_length = $length - (strlen($data) - $dot_position);
            if ($repeat_length > 0) {
                $data .= str_repeat('0', $repeat_length);
            }
            //小数点向后移n位
            $dot_position += $length;
            $data = ltrim(substr($data, 0, $dot_position), "0") . "." . substr($data, $dot_position);
        } elseif ($length < 0) {
            //当前是一个负数
            //获取要重复的0的个数
            $repeat_length = abs($length) - $dot_position;
            if ($repeat_length > 0) {
                //这里的值可能是小于0的数，由于小数点过长
                $data = str_repeat('0', $repeat_length) . $data;
            }
            $dot_position += $length;//此处length为负数，直接操作
            if ($dot_position < 1) {
                //补充数据处理，如果当前位置小于0则表示无需处理，直接补小数点即可
                $data = ".{$data}";
            } else {
                $data = substr($data, 0, $dot_position) . "." . substr($data, $dot_position);
            }
        }
        if ($data[0] == ".") {
            //数据补0
            $data = "0{$data}";
        }
        return trim($data, ".");
    }

    /**
     * 处理日期
     */
    public static function Processing_Date($str)
    {
        //判断如果数据是数组，转成字符串返回
        if (is_array($str)) {
            $temp = implode($str);
            $str = $temp;
        }
        //过滤非时间字符
        $str = preg_replace('/^[^\(]*\(/is', '', $str);
        $str = str_replace(["["], ' ', $str);
        $str = str_replace(["]"], ' ', $str);
        $str = str_replace(["|"], ' ', $str);
        $str = str_replace(["年", "月"], '-', $str);
        $str = str_replace(["日"], ' ', $str);
        $str = preg_replace('/([\x80-\xff]*)/i', '', $str);
        $str = str_replace(["/"], '-', $str);
        $str = trim($str);
        $str = substr($str, 0, 10);
        $str = trim($str);
        return $str;
    }

    /**
     *
     * 简单对称加密算法之加密
     * @param String $string 需要加密的字串
     * @param String $skey 加密EKY
     * @return String
     */
    public static function tokenEncode($string = '', $skey = '')
    {
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key < $strCount && $strArr[$key] .= $value;
        return str_replace(array(
            '=',
            '+',
            '/'
        ), array(
            'O0O0O',
            'o000o',
            'oo00o'
        ), join('', $strArr));
    }

    /**
     *
     * 简单对称加密算法之解密
     * @param String $string 需要解密的字串
     * @param String $skey 解密KEY
     * @return String
     */
    public static function tokenDecode($string = '', $skey = '')
    {
        $strArr = str_split(str_replace(array(
            'O0O0O',
            'o000o',
            'oo00o'
        ), array(
            '=',
            '+',
            '/'
        ), $string), 2);
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key <= $strCount && isset($strArr[$key]) && isset($strArr[$key][1])
            && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        return json_decode(base64_decode(join('', $strArr)), true);
    }

    /**
     * 统一校验输入字段内容长度
     * @param $field string 要验证的字段值
     * @param $start int 最小长度
     * @param $end int 最大长度
     * @param string $name 自定义的提示字段名称
     * @return string
     */
    public static function checkInputFieldLen($field, $start, $end, $name = '内容')
    {
        $nameLen = mb_strlen($field);
        $msg = '';
        //字段输入内容长度不少于$start个字符，大于$end个字符
        if ($nameLen < $start || $nameLen > $end) {
            $msg = "输入的$name" . "不能少于$start" . "字大于$end" . "字！";
        }
        return $msg;
    }

    /**
     * 校验只含 中文/字母/数字/下划线/点/破折线
     * @param $name
     * @return bool
     */
    public static function checkNameFormat($name)
    {
        $regEx = "/^[\x{4e00}-\x{9fa5}A-Za-z0-9_·•-]+$/u";//只匹配：中文/字母/数字/下划线/点/破折线
        if (!preg_match($regEx, $name)) {
            return false;
        }
        return true;
    }


    /**
     * 根据身份证获取生日信息
     * @param $name
     * @return bool
     */
    public static function getIDCardInfo($IDCard, $format = 1)
    {
        $result['error'] = 0;//0：未知错误，1：身份证格式错误，2：无错误
        $result['flag'] = '';//0标示成年，1标示未成年
        $result['tdate'] = '';//生日，格式如：2012-11-15
        if (!preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/", $IDCard)) {
            $result['error'] = 1;
            return $result;
        } else {
            if (strlen($IDCard) == 18) {
                $tyear = intval(substr($IDCard, 6, 4));
                $tmonth = intval(substr($IDCard, 10, 2));
                $tday = intval(substr($IDCard, 12, 2));
            } elseif (strlen($IDCard) == 15) {
                $tyear = intval("19" . substr($IDCard, 6, 2));
                $tmonth = intval(substr($IDCard, 8, 2));
                $tday = intval(substr($IDCard, 10, 2));
            }

            if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
                $flag = 0;
            } elseif ($tmonth < 0 || $tmonth > 12) {
                $flag = 0;
            } elseif ($tday < 0 || $tday > 31) {
                $flag = 0;
            } else {
                if ($format) {
                    $tdate = $tyear . "-" . $tmonth . "-" . $tday;
                } else {
                    $tdate = $tmonth . "-" . $tday;
                }

                if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
                    $flag = 0;
                } else {
                    $flag = 1;
                }
            }
        }
        $result['error'] = 2;//0：未知错误，1：身份证格式错误，2：无错误
        $result['isAdult'] = $flag;//0标示成年，1标示未成年
        $result['birthday'] = $tdate;//生日日期
        return $result;
    }

    //获取两点之间的距离,返回英里、英尺、码、公里、米
    public static function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2)
    {
        $theta = $longitude1 - $longitude2;
        $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
        $miles = acos($miles);
        $miles = rad2deg($miles);
        $miles = $miles * 60 * 1.1515;
        $feet = $miles * 5280;
        $yards = $feet / 3;
        $kilometers = $miles * 1.609344;
        $meters = $kilometers * 1000;
        return compact('miles', 'feet', 'yards', 'kilometers', 'meters');
    }

    //获取地址周边
    public static function getDistance($lat, $lng)
    {
        //获取该点周围的4个点
        $distance= \think\Config::get("site.distance");//范围（单位千米）
        if(empty($distance)) {
            $distance = 0.1;
        }
        $earth_radius= \think\Config::get("site.earth_radius");//地球半径，平均半径为6371km
        if(empty($earth_radius)) {
            $earth_radius = 6371;
        }
        $dlng = 2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance/$earth_radius;
        $dlat = rad2deg($dlat);
        $squares = array('left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
        'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
        'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
        'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
        );
        return $squares;
    }

    //获取同步数据
    public static function getSynchronism($url,$header,$content)
    {
        $ch = curl_init();//初始化curl
        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置header
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($content));
        $data = curl_exec($ch);//运行ch
        //file_put_contents(rand(10000, 99999).'.json', $data);
        if($error=curl_error($ch)){
            Log::error("同步数据错误：".$error);
        }
        //var_dump("未获取错误");
        //var_dump($data);
        //exit;
        curl_close($ch);
        $result = json_decode($data,true);
        return $result;
    }

    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后，求之前可以采用泰勒公式)
     * @param string $date1
     * @param string $date2
     * @return number
     */
    public static function diff_date($date1, $date2)
    {
        $msg = '';
        if ($date1 > $date2) {
            $msg = 'expired';
            $startTime = strtotime($date1);
            $endTime = strtotime($date2);
        }
        else {
            $msg = 'mature';
            $startTime = strtotime($date2);
            $endTime = strtotime($date1);
        }
        $diff = $startTime - $endTime;
        $day = $diff / 86400;

        if($msg === 'expired') {
            return '已过期'.intval($day).'天';
        }
        else {
            return intval($day).'天后到期';
        }
    }
}
